import moment from 'moment'

const dateFormat = function (dateStr, pattern = 'YYYY-MM-DD HH:mm:ss') {
  if (dateStr) {
    return moment(dateStr).format(pattern);
  } else {
    return '';
  }
}

//数值千分位
Number.prototype.toThousands = function () {
  var num = this.toString(), dotsub = "", result = '';
  if (num.indexOf(".") >= 0) {
    var sps = num.split(".");
    num = sps[0];
    dotsub = "." + sps[1];
  }
  while (num.replace('-', '').length > 3) {
    result = ',' + num.slice(-3) + result;
    num = num.slice(0, num.length - 3);
  }
  if (num) {
    result = num + result;
  }
  return result + dotsub;
};

//度量数值格式化
Number.prototype.toMeasureFormart = function (numberFormat) {
  if (numberFormat === undefined) {
    numberFormat = {};
    numberFormat.num_format_e = 0;
    numberFormat.num_format_s = -1;
    numberFormat.num_format_p = { prefix: "", subfix: "" };
    numberFormat.num_format_i = true;
  }
  var num = this;
  var sPre = "";
  if (numberFormat.num_format_s > -1) {
    num = num / (10000 * numberFormat.num_format_s);
    if (numberFormat.num_format_s === 1) {
      sPre = "万";
    }
    else if (numberFormat.num_format_s === 100) {
      sPre = "百万";
    }
    else if (numberFormat.num_format_s === 1000) {
      sPre = "千万";
    }
    else if (numberFormat.num_format_s === 10000) {
      sPre = "亿";
    }
    else if (numberFormat.num_format_s === 0.01) {
      sPre = "%";
      num = num * (10000 * numberFormat.num_format_s) * 100;
    }
  }
  num = num.toFixed(numberFormat.num_format_e);
  if (numberFormat.num_format_i) {
    num = Number(num).toThousands();
  }
  var num_format_msg = numberFormat.num_format_p.prefix + num + sPre + numberFormat.num_format_p.subfix;
  return num_format_msg;
};

export {dateFormat}
